/**
 * Created by huangxiaolu on 2014/4/11.
 */
var http = require('http');
var net = require('net');
var url = require('url');

// Create an HTTP tunneling proxy
var proxy = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.on('data',function(chunk){
        console.log('body %s',chunk);
    });
    res.end('okay');
});
proxy.on('connect', function(req, cltSocket, head) {
    // connect to an origin server
    var srvUrl = url.parse('http://' + req.url);
    var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
        cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
            'Proxy-agent: Node-Proxy\r\n' +
            '\r\n');
        srvSocket.write(head);
        srvSocket.pipe(cltSocket);
        cltSocket.pipe(srvSocket);
    });
});

var port = process.env.PORT || 8000;
// now that proxy is running
proxy.listen(port, '127.0.0.1', function() {
    console.log('proxy is listening on port %s' , port);
/*
    // make a request to a tunneling proxy
    var options = {
        port: 8000,
        hostname: '127.0.0.1',
        method: 'CONNECT',
        path: 'www.bing.com:80'
    };

    var req = http.request(options);
    req.end();

    req.on('connect', function(res, socket, head) {
        console.log('got connected!');

        // make a request over an HTTP tunnel
        socket.write('GET / HTTP/1.1\r\n' +
            'Host: www.bing.com:80\r\n' +
            'Connection: close\r\n' +
            '\r\n');
        socket.on('data', function(chunk) {
            console.log(chunk.toString());
        });
        socket.on('end', function() {
            proxy.close();
        });
    });*/
});